package com.example.blog.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import com.example.blog.entity.Admin;
import com.example.blog.entity.AdminActionLog;
import com.example.blog.mapper.AdminActionLogMapper;
import com.example.blog.mapper.AdminMapper;
import com.example.blog.service.AdminService;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;
    
    @Autowired
    private AdminActionLogMapper adminActionLogMapper;
    
    @Override
    public Map<String, Object> login(String loginName, String password) {
        Map<String, Object> map = new HashMap<>();
        
        try {
            // 查询管理员
            Admin admin = adminMapper.selectByLoginName(loginName);
            if (admin == null) {
                map.put("success", false);
                map.put("message", "管理员不存在");
                return map;
            }
            
            // 验证密码
            String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
            if (!admin.getPassword().equals(encryptedPassword)) {
                map.put("success", false);
                map.put("message", "密码错误");
                return map;
            }
            
            // 验证管理员状态
            if (admin.getIsDisabled()) {
                map.put("success", false);
                map.put("message", "账号已被禁用");
                return map;
            }
            
            // 登录成功
            map.put("success", true);
            map.put("message", "登录成功");
            map.put("admin", admin);
            
            // 不返回密码
            admin.setPassword(null);
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", "系统异常：" + e.getMessage());
        }
        
        return map;
    }

    @Override
    @Transactional
    public Map<String, Object> addAdmin(Admin admin) {
        Map<String, Object> map = new HashMap<>();
        
        try {
            // 验证登录名是否存在
            Admin existingAdmin = adminMapper.selectByLoginName(admin.getLoginName());
            if (existingAdmin != null) {
                map.put("success", false);
                map.put("message", "登录名已存在");
                return map;
            }
            
            // 加密密码
            admin.setPassword(DigestUtils.md5DigestAsHex(admin.getPassword().getBytes()));
            
            // 默认启用
            admin.setIsDisabled(false);
            
            // 插入管理员记录
            int result = adminMapper.insert(admin);
            if (result > 0) {
                map.put("success", true);
                map.put("message", "添加成功");
                map.put("adminId", admin.getAdminId());
            } else {
                map.put("success", false);
                map.put("message", "添加失败");
            }
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", "系统异常：" + e.getMessage());
        }
        
        return map;
    }

    @Override
    public Admin getAdminById(Integer adminId) {
        Admin admin = adminMapper.selectByPrimaryKey(adminId);
        if (admin != null) {
            // 不返回密码
            admin.setPassword(null);
        }
        return admin;
    }

    @Override
    public Admin getAdminByLoginName(String loginName) {
        Admin admin = adminMapper.selectByLoginName(loginName);
        if (admin != null) {
            // 不返回密码
            admin.setPassword(null);
        }
        return admin;
    }

    @Override
    public List<Admin> getAllAdmins() {
        List<Admin> admins = adminMapper.selectAll();
        
        // 不返回密码
        for (Admin admin : admins) {
            admin.setPassword(null);
        }
        
        return admins;
    }

    @Override
    @Transactional
    public boolean updateAdmin(Admin admin) {
        try {
            // 查询原管理员信息
            Admin originalAdmin = adminMapper.selectByPrimaryKey(admin.getAdminId());
            if (originalAdmin == null) {
                return false;
            }
            
            // 如果修改了密码，需要加密
            if (admin.getPassword() != null && !admin.getPassword().isEmpty()) {
                admin.setPassword(DigestUtils.md5DigestAsHex(admin.getPassword().getBytes()));
            } else {
                // 如果没有修改密码，使用原密码
                admin.setPassword(originalAdmin.getPassword());
            }
            
            int result = adminMapper.updateByPrimaryKey(admin);
            return result > 0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    @Transactional
    public boolean updateAdminStatus(Integer adminId, Boolean isDisabled) {
        try {
            int result = adminMapper.updateStatus(adminId, isDisabled);
            return result > 0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    @Transactional
    public boolean deleteAdmin(Integer adminId) {
        try {
            int result = adminMapper.deleteByPrimaryKey(adminId);
            return result > 0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    @Transactional
    public boolean addActionLog(AdminActionLog log) {
        try {
            // 设置操作时间
            log.setActionTime(new Date());
            
            int result = adminActionLogMapper.insert(log);
            return result > 0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public List<AdminActionLog> getActionLogs() {
        return adminActionLogMapper.selectAll();
    }

    @Override
    public List<AdminActionLog> getActionLogsByAdminId(Integer adminId) {
        return adminActionLogMapper.selectByAdminId(adminId);
    }

    @Override
    public List<AdminActionLog> getActionLogsByUserId(Integer userId) {
        return adminActionLogMapper.selectByUserId(userId);
    }

    @Override
    public List<AdminActionLog> getActionLogsByType(String actionType) {
        return adminActionLogMapper.selectByActionType(actionType);
    }

    @Override
    public List<AdminActionLog> getActionLogsByTimeRange(Date startTime, Date endTime) {
        return adminActionLogMapper.selectByTimeRange(startTime, endTime);
    }
} 